var xhr_object = null;

if(window.XMLHttpRequest) // Firefox
	xhr_object = new XMLHttpRequest();
else if(window.ActiveXObject) // Internet Explorer
	xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
else { // XMLHttpRequest unsupported
	alert('Votre navigateur ne supporte pas les objets XMLHTTPRequest...');
}



xhr_object.onreadystatechange = function() {
    if(xhr_object.readyState == 4){
	eval(xhr_object.responseText);
	initialize();
    }
}

xhr_object.open('GET','/vente/recupprod', true);


//xhr_object.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr_object.send(null);

	// currently displayed products
var folder = Array();

	// ids for products in cart
var sales = Array();

	// quantities for products in cart
var sales_num = Array();

	// current product selected
var current = 0;

	// current product selected in the cart
var current_sale = -1;

	// tab currently selected
var current_tab = 0; // 0 = products | 1 = sales

	// folder currently selected
var current_folder = -1; 

	// price for the entire cart
var total = 0.;

	// Research activated
var research = false;

	// Scanning a codebar
var scan_codebar = false;

	// scanned codebar
var codebar = '';

	// codebar active
var codebar_active = 0;

	// Credit for the scanned codebar
var solde_cb = 0;

	// Login pop-up
var login_pop = false;

	// Special prices activation
var special = false;

        // Is the sale done ?
var sale_done = false;

// Seek the place of 'id' in 'array'

function seek_id(id, array) {
	return array.indexOf(id);
}

// Scroll to an object

function ScrollTo(obj){
	obj.scrollIntoView(true);
}

// Calculate total

function calculate_total() {
	var result = 0.;
	
	if (codebar_active == 0 && !special) {
		var array = prix;
	}
	else if (special) {
		var array = prix_special;
	}
	else {
		var array = prix_cb;
	}
	
	for (i = 0 ; i < sales.length ; i++) {
		result += sales_num[i] * array[seek_id(sales[i],produits_id)];
	}
	
	total = result;
	document.getElementById('total').innerHTML = Math.floor(100 * total) / 100 + ' €';
	if (document.getElementById('solde') && solde_cb < total) {
		document.getElementById('solde').style.background = 'red';
	}
	else if (document.getElementById('solde')) {
		document.getElementById('solde').style.background = 'url(\'css/button_selected.png\')';
	}
}

// Search the id for items containing 'str'

function SearchProduct(array, array_id, str) {
	var result = Array();
	var re = new RegExp(str,'i');
	for (i = 0 ; i < array.length ; i++) {
		if (re.test(array[i])) {
			result.push(array_id[i]);
		}
	}
	
	return result;
}

// Add a sale

function add_vente(id_prod) {
	
	// if product not in cart, create it
	if (!document.getElementById('sale_' + id_prod)) {
		var new_vente = document.createElement('li');
		new_vente.id = 'sale_' + id_prod;
		new_vente.innerHTML =
			'<button type="button" id="saleprod_' + id_prod +'">' + produits[seek_id(id_prod,produits_id)] + '</button>' + 
			'<button type="button" class="sales" id="sales_' + id_prod + '">1</button>' +
			'<div class="plusminus">' +
			'<button type="button" class="plus" onclick="add_vente(\'' + id_prod + '\')">+</button>' +
			'<button type="button" class="minus" onclick="remove_vente(\'' + id_prod + '\')">-</button>' +
			'</div>';
		
		document.getElementById('vente').appendChild(new_vente);
		sales.push(id_prod);
		sales_num.push(1);
	}
	// if product in cart, just add 1
	else {
		document.getElementById('sales_' + id_prod).innerHTML = parseInt(document.getElementById('sales_' + id_prod).innerHTML) + 1;
		sales_num[seek_id(id_prod, sales)]++;
	}
	
	// update total
	document.getElementById('selected_products').value = sales.join(',');
	document.getElementById('selected_qqties').value = sales_num.join(',');
	calculate_total();
}

// Remove a sale

function remove_vente(id_prod) {
	if (document.getElementById('sale_' + id_prod)) {
		
		// if only one of this product in cart, remove it
		if (document.getElementById('sales_' + id_prod).innerHTML == 1) {
			document.getElementById('vente').removeChild(document.getElementById('sale_' + id_prod));
			sales_num.splice(seek_id(id_prod, sales), 1);
			sales.splice(seek_id(id_prod, sales), 1);
			
			// update current_sale
			current_sale--;
			if (current_sale == -1 && sales.length > 0) {
				current_sale = 0;
			}
			else if (current_sale >= 0 && sales.length == 0) {
				current_sale = -1;
			}
			if (current_sale >= 0 && current_sale < sales.length && sales.length > 0) {
				document.getElementById('sale_' + sales[current_sale]).setAttribute('class', 'selected');
				document.getElementById('sale_' + sales[current_sale]).focus();
			}
		}
		
		// remove 1 if more than two entries for this product
		else {
			document.getElementById('sales_' + id_prod).innerHTML = parseInt(document.getElementById('sales_' + id_prod).innerHTML) - 1;
			sales_num[seek_id(id_prod, sales)]--;
		}
	}
	
	// update total
	document.getElementById('selected_products').value = sales.join(',');
	document.getElementById('selected_qqties').value = sales_num.join(',');
	calculate_total();
	
	if (sales.length == 0) {
		current_sale = -1;
		total = 0;
		document.getElementById('total').innerHTML = '0 €';
	}
}

// Get folder's content

function get_folder_content(folder_id) {
	var result = Array();
	for (k = 0 ; k < prod_folder.length ; k++) {
		if (prod_folder[k] == folder_id) {
			result.push(produits_id[k]);
		}
	}
	
	return result;
}

// bring the folder's content to the screen

function load_folder(folder_id) {
	folder = get_folder_content(folder_id);
	
	current = current_folder;
	if (folder_id != -1 || current_folder == -1) {
		current = 0;
	}
	current_folder = seek_id(folder_id,folders_id);
		
	document.getElementById('produits').innerHTML = '';
	
	// Load folders
	
	if (current_folder == -1) {
		for (i = 0 ; i < folders.length ; i++) {
			var j = i;
			var new_folder = document.createElement('li');
			new_folder.id = 'prod_' + folders_id[j];
			new_folder.num = folders_id[j];
			new_folder.innerHTML =
				'<button type="button">' + folders[j] + '</button>' +
				'<button type="button" class="price">&#9654;</button>';
			
			document.getElementById('produits').appendChild(new_folder);
		
			new_folder.addEventListener('click', function() {
				load_folder(this.num);	
			}, false);
		}
	}
	
	// Load products
	
	for (i = 0 ; i < folder.length ; i++) {
		var j = i;
		var new_prod = document.createElement('li');
		new_prod.id = 'prod_' + folder[j];
		new_prod.num = folder[j];
		new_prod.innerHTML =
			'<button type="button">' + produits[seek_id(folder[j],produits_id)] + '</button>' +
			'<button type="button" class="price"><span class="prix' + codebar_active + '">' + prix[seek_id(folder[j],produits_id)] + ' €</span><span class="prix' + (1 - codebar_active) + '">' + prix_cb[seek_id(folder[j],produits_id)] + ' €</span></button>';
		
		document.getElementById('produits').appendChild(new_prod);
		
		new_prod.addEventListener('click', function() {
			add_vente(this.num);
			ScrollTo(document.getElementById('sale_' + sales[Math.max(0,Math.min(sales.length - 1,seek_id(this.num, sales) - 2))]));	
		}, false);
	}
	if (folder_id != -1 && folder.length > 0) {
		document.getElementById('prod_' + folder[0]).setAttribute('class', 'selected');
	}
	else if (folders_id.length > 0) {
		document.getElementById('prod_' + folders_id[current]).setAttribute('class', 'selected');
		document.getElementById('prod_' + folders_id[current]).focus();
	}
}

// research a product from what's typed on the keyboard

function research_prod(e) {
	load = false;
	
	if (research && (e.which >= 65 && e.which <= 90 && !e.metaKey) || (e.which >= 96 && e.which <= 105 && !e.metaKey)) { // only a-z and 0-9 accepted
					
		load = true;
		// Hide products
		document.getElementById('produits_block').style.display = 'none';
		document.getElementById('produits').innerHTML = '';
		
		// Show Results
		if (!document.getElementById('search_block')) {
			var search_block = document.createElement('div');
			search_block.id = 'search_block';
			if (current_tab == 1) {
				document.getElementById('vente_block').className = 'block';
			}
			search_block.className = 'block hover';
			document.getElementById('page_vente').insertBefore(search_block, document.getElementById('best'));
		}

		if (document.getElementById('search_block')) {
			if (temp = document.getElementById('args')) {
				se = temp.value;
			}
			else se = '';
			
			document.getElementById('search_block').innerHTML =
				'<h2>Produits&nbsp;&nbsp;<input type="text" id="args" value="' + se + '" /></h2>' +
				'<ul id="search"></ul>';
		}
		
		if(e.which >= 96) {
			document.getElementById('args').value += e.which - 96;
		}
		else {
			document.getElementById('args').value += String.fromCharCode(e.which).toLowerCase();
		}
		
		folder = SearchProduct(produits,produits_id,document.getElementById('args').value);
	}
	
	// Capture deletions
	
	else if (e.which == 8 && document.getElementById('search_block')) {
		var search = document.getElementById('args').value;
		
		if (temp = document.getElementById('args')) {
			se = temp.value;
		}
		else se = '';
		
		document.getElementById('search_block').innerHTML =
			'<h2>Produits&nbsp;&nbsp;<input type="text" id="args" value="' + se + '" /></h2>' +
			'<ul id="search"></ul>';
					
		if (search.length <= 1) {
			document.getElementById('args').value = '';
			if (temp = document.getElementById('search_block')) {
				document.getElementById('page_vente').removeChild(temp);
				document.getElementById('produits_block').style.display = 'block';
				current_folder = -1;
				load_folder(-1);
				current_tab = 0;
				research = false;
			}
		}
		else {
			load = true;
			document.getElementById('args').value = search.slice(0, search.length - 1);
			folder = SearchProduct(produits,produits_id,document.getElementById('args').value);
		}
	}
	
	if (folder.length == 0 && document.getElementById('args') && load && research) {
		document.getElementById('args').style.background = 'red';
		document.getElementById('args').style.color = 'white';
	}
	
	if (load && folder.length > 0) {
		current_tab = 0;
		current_folder = -2;
		current = 0;
		
		for (i = 0 ; i < folder.length ; i++) {
			var j = i;
			var new_prod = document.createElement('li');
			new_prod.id = 'prod_' + folder[j];
			new_prod.num = folder[j];
			new_prod.innerHTML =
				'<button type="button">' + produits[seek_id(folder[j],produits_id)] + '</button>' +
				'<button type="button" class="price">' + prix[seek_id(folder[j],produits_id)] + ' €</button>';

			document.getElementById('search').appendChild(new_prod);

			new_prod.addEventListener('click', function() {
				add_vente(this.num);
				ScrollTo(document.getElementById('sale_' + sales[Math.max(0,Math.min(sales.length - 1,seek_id(this.num, sales) - 2))]));	
			}, false);
		}
		document.getElementById('prod_' + folder[0]).setAttribute('class', 'selected');
	}
}

// What to do when a CodeBar is scanned

function scanning_codebar(login, solde) {
	solde_cb = solde;
	
	if (codebar_active == 0) {
		document.getElementById('buttons').getElementsByTagName('h2')[0].innerHTML += ' - ' + login;
	    document.getElementById('login').value = login;
		var solde_button = document.createElement('button');
		solde_button.type = 'button';
		solde_button.id = 'solde';
		solde_button.innerHTML = Math.floor(100 * solde) / 100 + ' €';
		document.getElementById('buttons').insertBefore(solde_button, document.getElementById('reset'));
		
		var br = document.createElement('br');
		document.getElementById('buttons').insertBefore(br, document.getElementById('reset'));
		
		for( i = 0 ; i < document.getElementsByClassName('prix0').length ; i++) {
			document.getElementsByClassName('prix0')[i].style.display = 'none';
			document.getElementsByClassName('prix1')[i].style.display = 'inline';
		}
	}
	
	codebar_active = 1;
	calculate_total();
}

function initialize() {
	
	// Scan codebar or execute research
	
	document.addEventListener('keydown', function(e) {
		if (login_pop) {
			return false;
		}
		
		if ((e.which >= 65 && e.which <= 90) || (e.which >= 96 && e.which <= 105) || (e.which >= 48 && e.which <= 57) || e.which == 8) {
			scan_codebar = true;
			research = true;
			codebar += String.fromCharCode(e.which);
			
			setTimeout(function() {scan_codebar = false; codebar = ''; research_prod(e)}, 600);
		}
		else if (codebar != '' && e.which == 13) {
			research = false;
			var xhr = null;

		    if(window.XMLHttpRequest) // Firefox
			xhr = new XMLHttpRequest();
		    else if(window.ActiveXObject) // Internet Explorer
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		    else { // XMLHttpRequest unsupported
			alert('Votre navigateur ne supporte pas les objets XMLHTTPRequest...');
		    }



		    xhr.onreadystatechange = function() {
			if(xhr.readyState == 4){
			    eval(xhr.responseText);
			}
		    }

		    xhr.open('GET','/vente/infocodebarres?codebar='+codebar+'&vente_login=0', true);		  

		    //xhr_object.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		    xhr.send(null);	    
		}
		
	}, false);

	// Creation of the product list
	
	load_folder(-1);
	
	// Folder choice (handle left and right to navigate)
	
	document.addEventListener('keydown', function(e) {
		if (e.which == 37 && current_tab == 0 && current_folder != -1) { // left
			load_folder(-1);
		}
		else if (e.which == 39 && current_tab == 0 && current_folder == -1) { // right
			load_folder(folders_id[current]);
		}
	}, false);
	
	// Product choice (handle up and down to navigate)
	
	document.addEventListener('keydown', function(e) {
		
		if (current_tab == 0) {
			// Choose the good array : folders or products
			
			var browse = Array();
			if (current_folder == -1) {
				browse = folders_id;
			}
			else {
				browse = folder;
			}
			
			if (e.which == 38 && current > 0 && !login_pop) { // up
				document.getElementById('prod_' + browse[current - 1]).setAttribute('class', 'selected');
				document.getElementById('prod_' + browse[current - 1]).focus();
				ScrollTo(document.getElementById('prod_' + browse[Math.max(0,Math.min(browse.length - 1,current - 3))]));
				document.getElementById('prod_' + browse[current]).setAttribute('class', '');
						
				current--;
				if(e.preventDefault) {
					e.preventDefault();
				}
				return false;
			}
			else if (e.which == 40 && current < browse.length - 1 && !login_pop) { // down
				if (current >= 0) {
					document.getElementById('prod_' + browse[current + 1]).setAttribute('class', 'selected');
					document.getElementById('prod_' + browse[current + 1]).focus();
					ScrollTo(document.getElementById('prod_' + browse[Math.min(browse.length - 1,Math.max(0,current - 1))]));
					document.getElementById('prod_' + browse[current]).setAttribute('class', '');
				}
				else {
					document.getElementById('prod_' + browse[0]).setAttribute('class', 'selected');
					document.getElementById('prod_' + browse[0]).focus();
				}
			
				current++;
				if(e.preventDefault) {
					e.preventDefault();
				}
				return false;
			}
		}
		
		// Sale choice (handle up and down to navigate)
		
		else if (current_tab == 1) {
			if (e.which == 38 && current_sale > 0) { // up
				document.getElementById('sale_' + sales[current_sale - 1]).setAttribute('class', 'selected');
				document.getElementById('sale_' + sales[current_sale - 1]).focus();
				ScrollTo(document.getElementById('sale_' + sales[Math.max(0,Math.min(sales.length - 1,current_sale - 3))]));
				document.getElementById('sale_' + sales[current_sale]).setAttribute('class', '');
						
				current_sale--;
				if(e.preventDefault) {
					e.preventDefault();
				}
				return false;
			}
			else if (e.which == 40 && current_sale < sales.length - 1) { // down
				if (current_sale >= 0) {
					document.getElementById('sale_' + sales[current_sale + 1]).setAttribute('class', 'selected');
					document.getElementById('sale_' + sales[current_sale + 1]).focus();
					ScrollTo(document.getElementById('sale_' + sales[Math.max(0,Math.min(sales.length - 1,current_sale - 1))]));
					document.getElementById('sale_' + sales[current_sale]).setAttribute('class', '');
				}
				else {
					document.getElementById('sale_' + sales[0]).setAttribute('class', 'selected');
					document.getElementById('sale_' + sales[0]).focus();	
				}
			
				current_sale++;
				if(e.preventDefault) {
					e.preventDefault();
				}
				return false;
			}
			
			// handle left and right to remove or add product
			else if (e.which == 37 && current_sale >= 0) { // left
				remove_vente(sales[current_sale]);
			}
			else if (e.which == 39 && current_sale >= 0) { // right
				add_vente(sales[current_sale]);
			}
		}
	}, false);

	// Creation of the best-sellers

	for (k = 0 ; k < best_sellers.length ; k++) {
		var j = k;
		var new_best = document.createElement('li');
		new_best.id = 'best_' + best_sellers[j];
		new_best.num = best_sellers[j];
		new_best.innerHTML =
			'<button type="button" class="num">' + (k + 1) + '</button>' +
			'<button type="button" class="best">' + produits[seek_id(best_sellers[j],produits_id)] + '</button>' +
			'<button type="button" class="price"><span class="prix' + codebar_active + '">' + prix[seek_id(best_sellers[j],produits_id)] + ' €</span><span class="prix' + (1 - codebar_active) + '">' + prix_cb[seek_id(best_sellers[j],produits_id)] + ' €</span></button>';

		document.getElementById('best').appendChild(new_best);

		new_best.addEventListener('click', function() {
			add_vente(this.num);	
		}, false);
	}

	// Best-sellers choice (F1, F2 or F3 on the keyboard to select them)

	document.addEventListener('keydown', function(e) {
		for (j = 0 ; j < best_sellers.length ; j++) {
			i = j;
			if (e.which == 112 + i) { // 1
				add_vente(best_sellers[i]);
				ScrollTo(document.getElementById('sale_' + sales[Math.max(0,Math.min(sales.length - 1,seek_id(best_sellers[i], sales) - 2))]));
				
				if(e.preventDefault) {
					e.preventDefault();
				}
				return false;
			}
		}
	}, false);
	
	// Handle the spacebar (validate sale)
	
	document.addEventListener('keydown', function(e) {
		if (e.which == 32 && current >= 0 && current_tab == 0 && current_folder == -1) {
			load_folder(folders_id[current]);
		}
		else if (e.which == 32 && current >= 0 && current_tab == 0 && folder.length > 0) { // space
			add_vente(folder[current]);
			ScrollTo(document.getElementById('sale_' + sales[Math.max(0,Math.min(sales.length - 1,seek_id(folder[current], sales) - 2))]));
		}
		else if (e.which == 32 && current_sale >= 0 && current_tab == 1) { // space
			add_vente(sales[current_sale]);
		}
	}, false);
	
	// Handle the tab key (navigate between products and cart)
	
	document.addEventListener('keydown', function(e) {
		if(e.which == 9 && !login_pop) {
			if (temp = document.getElementById('search_block')) {
				document.getElementById('page_vente').removeChild(temp);
				document.getElementById('produits_block').style.display = 'block';
				current = 0;
				current_tab = 0;
				current_folder = -1;
				load_folder(-1);
				research = false;
			}
			
			current_tab = (current_tab + 1) % 2;
			
			// if the product list is selected
			if (current_tab == 0) {
				document.getElementById('produits_block').setAttribute('class','hover block');
				document.getElementById('vente_block').setAttribute('class','block');
				
				// deselect current sale
				if (current_sale >= 0 && current_sale < sales.length) {
					document.getElementById('sale_' + sales[current_sale]).setAttribute('class', '');
				}
			}
			
			// if the cart is selected
			else if (current_tab == 1) {
				ScrollTo(document.getElementById('sale_' + sales[0]));
				
				// deselect current product in cart
				if (sales.length != 0 && current_sale != -1) {
					document.getElementById('sale_' + sales[current_sale]).setAttribute('class', '');
				}
				
				// select the first product in cart
				if (sales.length > 0) {
					document.getElementById('sale_' + sales[0]).setAttribute('class', 'selected');
					document.getElementById('sale_' + sales[0]).focus();
					current_sale = 0;
				}
				
				document.getElementById('vente_block').setAttribute('class','hover block');
				document.getElementById('produits_block').setAttribute('class','block');
			}
			if(e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}
	}, false);
	
	// Handle the esc key (go back in the history)
	
	document.addEventListener('keyup', function(e) {
		if(e.which == 27) {
			//history.go(0);
			//history.go(-1);
			window.location = "/index/modulechoice";
			if(e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}
	}, false);
	
	// Handle the ctrl key (sell by login)
	
	document.addEventListener('keydown', function(e) {
		if (e.which == 17) {
			popup('popUpDiv');
		}
	}, false);

	// Handle the = key (special price activation)
	
	document.addEventListener('keydown', function(e) {
		if (e.which == 187) {
			special = !special;
			calculate_total();
			
			if (special) {
				document.getElementById('type').value = 2;
				document.getElementById('special').style.display = 'block';
			}
			else if (codebar != '') {
				document.getElementById('type').value = 1;
				document.getElementById('special').style.display = 'none';
			}
			else {
				document.getElementById('type').value = 0;
				document.getElementById('special').style.display = 'none';
			} 
		}
	}, false);
	
	// Handle the enter key (validate cart)
	
	document.addEventListener('keydown', function(e) {
		if (e.which == 13 && login_pop) {
			//ajax
		    var xhr_popup = null;

		    if(window.XMLHttpRequest) // Firefox
			xhr_popup = new XMLHttpRequest();
		    else if(window.ActiveXObject) // Internet Explorer
			xhr_popup = new ActiveXObject("Microsoft.XMLHTTP");
		    else { // XMLHttpRequest unsupported
			alert('Votre navigateur ne supporte pas les objets XMLHTTPRequest...');
		    }



		    xhr_popup.onreadystatechange = function() {
			if(xhr_popup.readyState == 4){
			    eval(xhr_popup.responseText);
			}
		    }

		    login_keyboard = document.getElementById('login_keyboard').value;
		    password_groupe = document.getElementById('password_groupe').value;

		    xhr_popup.open('GET','/vente/infocodebarres?codebar='+login_keyboard+'&vente_login=1&code='+password_groupe, true);		  

		    //xhr_object.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		    xhr_popup.send(null);
		        //fin ajax
			popup('popUpDiv');
			if(e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}
		
		if(e.which == 13 && !scan_codebar) {
			if (codebar_active == 1 && total > solde_cb) {
				alert('Solde insuffisant !');
			}
		        else if (!sale_done) {
   			        sale_done = true;
				document.forms['page_vente'].submit();
			}
			
			if(e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}
	}, false);
	
	// Handle the return key (disabled)

	document.addEventListener('keydown', function(e) {
		if(e.which == 8 && !login_pop) {
			if(e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}
	}, false);
}
